package library.server;

import java.sql.SQLException;
import java.util.List;

import javax.jws.WebService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

@WebService
public class LibraryServer {
	// private static final String USER = "root";
	// private static final String PASSWORD = "root";
	private DataSource ds = null;

	public LibraryServer() {
		if (ds == null) {
			Context initCtx;
			try {
				initCtx = new InitialContext();
				Context envCtx = (Context) initCtx.lookup("java:comp/env");
				ds = (DataSource) envCtx.lookup("jdbc/LibraryDB");
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public synchronized boolean addBook(Book b) {
		MySQLConnection connection;
		boolean result = false;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.insertBook(connection, b);
			connection.closeConnection();
		} catch (SQLException e) {
			result = false;
		}

		return result;
	}

	public synchronized boolean deleteBook(String isdn) {
		MySQLConnection connection;
		boolean result = false;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.deleteBook(connection, isdn);
			connection.closeConnection();
		} catch (SQLException e) {
			result = false;
		}

		return result;
	}

	public synchronized List<Book> getAllBooks() {
		MySQLConnection connection;
		List<Book> result;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.getAllBooks(connection);
			connection.closeConnection();
		} catch (SQLException e) {
			result = null;
		}

		return result;
	}

}
